package Response;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Registration extends HttpServlet {
	PreparedStatement ps=null;
	
	Connection con=null;
	public void init() throws ServletException 
	{
		try 
		{

			Class.forName("com.mysql.jdbc.Driver");
			String url="jdbc:mysql://localhost:3306/websurvey";
			con=DriverManager.getConnection(url, "root", "mysql");
			System.out.println("connection established");
			
		} 
		catch (ClassNotFoundException e) 
		{
			e.printStackTrace();
		} catch (SQLException e) 
		{
			e.printStackTrace();
		}
		
	}
	

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		try 
		{
			out.println("hello");
			PreparedStatement ps=con.prepareStatement("insert into registration(fname,lname,email,contact)values(?,?,?,?)");
			out.println("obtained data..");
		String fnm=request.getParameter("fname");
		out.println(fnm);
		String lnm=request.getParameter("lname");
		out.println(lnm);
		String email=request.getParameter("email");
		out.println(email);
		String pass=request.getParameter("contact");
		out.println(pass);
		//int contact=Integer.parseInt(request.getParameter("contact"));
		//out.println("new number"+contact);
		
			ps.setString(1, fnm);
			ps.setString(2, lnm);
			ps.setString(3, email);
			ps.setString(4,pass);

			out.println("hello");
			int n=ps.executeUpdate();
			out.println(n+" rows inserted");
			//ps.close();
			
			String pass1=pass.substring(3, 7);
			out.println(pass1);
			String password=fnm.concat(pass1);
			out.println(password);
			
			PreparedStatement pstmt=con.prepareStatement("insert into login (email,password)values(?,?)");
			pstmt.setString(1, email);
			pstmt.setString(2,password);
			
			int d=pstmt.executeUpdate();
			out.println(d+" row inserted");
			pstmt.close();
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		out.flush();
		out.close();
	}

	
	
	public void destroy()
	{
		
		super.destroy(); 
	}

}
